<template>
  <div>
    <!-- M面包屑 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加按钮 -->
      <el-row>
        <el-col>
          <el-button type="success">添加</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 角色列表 -->
    <el-table :data="rolesList" border>
      <!-- 展开 -->
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row
            :class="['bdbottom',index1 ===0 ? 'bdtop':'','vcenter']"
            v-for="(item1,index1) in scope.row.children"
            :key="item1.id"
          >
            <!-- 一级 -->
            <el-col :span="5">
              <el-tag closable @close="deleRoles(scope.row,item1.id)">{{item1.authName}}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 二三级 -->
            <el-col :span="19">
              <el-row
                :class="[index2===0?'':'bdtop','vcenter']"
                v-for="(item2,index2) in item1.children"
                :key="item2.id"
              >
                <!-- 二级 -->
                <el-col :span="6">
                  <el-tag closable @close="deleRoles(scope.row,item2.id)">{{item2.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 三级 -->
                <el-col :span="18">
                  <el-tag
                    v-for="item3 in item2.children"
                    :key="item3.id"
                    closable
                    @close="deleRoles(scope.row,item3.id)"
                  >{{item3.authName}}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column type="index" label="序号"></el-table-column>
      <el-table-column prop="roleName" label="角色名称"></el-table-column>
      <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
      <el-table-column>
        <template slot-scope="scope">
          <!-- 修改 -->
          <el-button type="primary" icon="el-icon-edit" circle></el-button>
          <!-- 删除 -->
          <el-button type="info" icon="el-icon-delete" circle></el-button>
          <!-- 分配角色 -->
          <el-button type="warning" icon="el-icon-setting" circle @click="editRoles(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分配角色弹窗 -->
    <el-dialog
      title="分配角色"
      :visible.sync="editRolesDialogVisible"
      width="50%"
      @close="clearTreeDefKeys"
    >
      <!-- 树结构 -->
      <el-tree
        :data="rightsTreeList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="treeDefKeys"
        ref="roleTree"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="postRoleTree">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表
      rolesList: [],
      // 分配弹窗显示
      editRolesDialogVisible: false,
      // 所有权限列表
      rightsTreeList: [],
      // 树属性
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 树默认选中的key
      treeDefKeys: [],
      // 点击分配角色按钮的角色id
      roleID: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取列表失败')
      }
      this.rolesList = res.data
      // console.log(this.rolesList)
    },
    // 删除权限
    async deleRoles(roles, rightId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除账户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }

      const { data: res } = await this.$http.delete(
        `roles/${roles.id}/rights/${rightId}`
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      // 把返回的数据传给参数的children就能实现不刷新删除
      roles.children = res.data
    },
    // 点击分配角色
    async editRoles(role) {
      this.roleID = role.id
      // console.log(this.roleID)
      // 获取所有权限列表
      const { data: res } = await this.$http.get('rights/tree')
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取所有权限列表失败')
      }
      this.rightsTreeList = res.data
      // console.log(this.rightsTreeList)
      // 递归获取三级id
      this.getLastID(role, this.treeDefKeys)
      this.editRolesDialogVisible = true
    },
    // 递归获取所有三级id
    getLastID(role, arr) {
      if (!role.children) {
        return arr.push(role.id)
      }

      role.children.forEach(item => {
        this.getLastID(item, arr)
      })
    },
    // 点其他分配按钮时的保存的数组越来越多的bug
    clearTreeDefKeys() {
      this.treeDefKeys = []
    },
    // 勾选树结构发请求
    async postRoleTree() {
      // 定义一个数组保存 分割的权限 ID 列表
      const roleKeys = [
        ...this.$refs.roleTree.getCheckedKeys(),
        ...this.$refs.roleTree.getHalfCheckedKeys()
      ]
      // console.log(roleKeys)
      // 以 `,` 分割的权限 ID 列表
      const roleKeysToStr = roleKeys.join(',')
      // 发请求
      const { data: res } = await this.$http.post(
        `roles/${this.roleID}/rights`,
        { rids: roleKeysToStr }
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('更新失败')
      }
      this.$message.success('更新成功')
      this.getRolesList()
      this.editRolesDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
</style>
